package com.heima.comment.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentLikeVo;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private CommentHotService commentHotService;

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) throws Exception {
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if (userId == 0) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> userById = userFeign.findUserById(userId);
        ApUser apUser = userById.getData();
        String content = dto.getContent();
        if (content.length() > 140) {
            CustException.cust(AppHttpCodeEnum.EXCEED_BOUND);
        }
        //阿里云文本检测
        ScanResult scanResult = greenScan.greenTextScan(content);
        System.err.println("scanResult = " + scanResult);
        //过滤敏感词之后的评论
        String filteredContent = scanResult.getFilteredContent();
        System.err.println("filteredContent = " + filteredContent);
        if (StringUtils.isBlank(filteredContent) && !scanResult.getSuggestion().equals("pass")) {
            CustException.cust(AppHttpCodeEnum.COMMENT_FAILURE);
        }

        ResponseResult<ApArticle> responseResult = articleFeign.queryByArticleId(dto.getArticleId());
        ApArticle apArticle = responseResult.getData();
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(userId);
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        //频道id
        apComment.setChannelId(apArticle.getChannelId());
        if (filteredContent == null) {
            apComment.setContent(content);
        } else {
            apComment.setContent(filteredContent);
        }
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        Short flag = apUser.getFlag();
        //是否大V
        if (flag == 2) {
            apComment.setFlag((short) 5);
        } else {
            apComment.setFlag((short) 0);
        }
        //经纬度,找不到
//        apComment.setLongitude(new BigDecimal("0"));
//        apComment.setLatitude(new BigDecimal("0"));
//        apComment.setAddress("");
//        apComment.setOrd(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        //mongo保存评论
        mongoTemplate.save(apComment);
        return ResponseResult.okResult("评论成功!");
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if (userId == 0) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Short operation = dto.getOperation();
        if (operation != 0 && operation != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该评论已删除");
        }
        if (operation == 0) {
            saveLikeComment(dto, userId, apComment);
            ApComment apComment1 = mongoTemplate.findOne(query, ApComment.class);
            Integer likes1 = apComment1.getLikes();
            ApCommentLikeVo apCommentLikeVo = new ApCommentLikeVo();
            apCommentLikeVo.setLikes((long) likes1);
            return ResponseResult.okResult(apCommentLikeVo);
        } else if (operation == 1) {
            deleteLikeComment(dto, userId, apComment);
            ApComment apComment1 = mongoTemplate.findOne(query, ApComment.class);
            Integer likes1 = apComment1.getLikes();
            ApCommentLikeVo apCommentLikeVo = new ApCommentLikeVo();
            apCommentLikeVo.setLikes((long) likes1);
            return ResponseResult.okResult(apCommentLikeVo);
        }
        return null;
    }

    /**
     * 评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApComment> findByArticleId(CommentDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        //校验size
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        //校验最小时间
        Date minDate = dto.getMinDate();
        if (minDate == null) {
            minDate = new Date();
        }
        //   ========================需要变更处 start =============================
        //2 查询Mongo文章所有评论列表
        List<ApComment> apCommentList = null;
        if (dto.getIndex().intValue() == 1) { // 判断当前是否是第一页评论
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query hotQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(1));
            hotQuery.with(Sort.by(Sort.Direction.DESC, "likes"));
            hotQuery.limit(5);
            List<ApComment> hotApComments = mongoTemplate.find(hotQuery, ApComment.class);
            // 新size = size - 热评数量
            Integer newSize = size - hotApComments.size();
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query commonQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(0));
            commonQuery.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            commonQuery.limit(newSize);
            List<ApComment> commonApComments = mongoTemplate.find(commonQuery, ApComment.class);
            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            if (hotApComments.size() > 0) {
                apCommentList = hotApComments;
            }
            if (commonApComments.size() > 0 && (apCommentList.size() == 0 || apCommentList == null)) {
                apCommentList = commonApComments;
            } else {
                assert apCommentList != null;
                apCommentList.addAll(commonApComments);
            }

        } else {
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(0)
                    .and("createdTime").lte(minDate));
            query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            query.limit(size);
            apCommentList = mongoTemplate.find(query, ApComment.class);
        }
        // ========================需要变更处 end =============================
//        //根据条件查询评论列表
//        //(文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
//        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
//                .and("createdTime").lte(minDate));
//        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
//        query.with(PageRequest.of(dto.getIndex() - 1, size));
//        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
//        System.err.println("apComments = " + apComments);
        List<ApCommentVo> apCommentVoList = new ArrayList<>();
        if (userId == 0) {
            // //3.1 用户未登录 直接返回评论列表
            return ResponseResult.okResult(apCommentList);
        } else {
            //3.2 用户登录，需要加载当前用户对评论点赞的列表
            //5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //              commentId  in    评论id列表   authorId = 登录人id
            for (ApComment apComment : apCommentList) {
                Query queryLike = Query.query(Criteria.where("authorId").is(userId)
                        .and("commentId").is(apComment.getId()));
                ApCommentLike apCommentLike = mongoTemplate.findOne(queryLike, ApCommentLike.class);
                System.err.println("apCommentLike = " + apCommentLike);
                //1. 5.2 遍历评论列表
                //           将每一个评论  ApComment 转成 ApCommentVO
                //             其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                if (apCommentLike != null) {
                    System.err.println("apCommentVo = " + apCommentVo);
                    apCommentVo.setOperation((short) 0);
                    apCommentVoList.add(apCommentVo);
                    continue;
                }
                apCommentVoList.add(apCommentVo);
            }
        }
        System.err.println("apCommentVoList = " + apCommentVoList);
        return ResponseResult.okResult(apCommentVoList);
    }


    /**
     * 删除点赞信息
     *
     * @param dto
     * @param userId
     * @param apComment
     */
    private void deleteLikeComment(CommentLikeDTO dto, Integer userId, ApComment apComment) {
        Query query = Query.query(Criteria.where("authorId").is(userId)
                .and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        if (apCommentLike != null) {
            //删除点赞信息
            mongoTemplate.remove(apCommentLike);
            //点赞数量-1,且不能为负数
            Query queryComment = Query.query(Criteria.where("id").is(dto.getCommentId()));
            Integer likes = apComment.getLikes() - 1;
            if (likes >= 0) {
                Update update = new Update();
                update.set("likes", likes);
                mongoTemplate.updateFirst(queryComment, update, ApComment.class);
            } else {
                //提示未点赞
                CustException.cust(AppHttpCodeEnum.NEED_UnLike, "未给此条评论点赞");
            }
        }
    }

    /**
     * 点赞操作
     *
     * @param dto
     * @param userId
     * @param apComment
     */
    private void saveLikeComment(CommentLikeDTO dto, Integer userId, ApComment apComment) {
        Query query = Query.query(Criteria.where("authorId").is(userId)
                .and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        if (apCommentLike == null) {
            //保存点赞
            ApCommentLike apCommentLike1 = new ApCommentLike();
            apCommentLike1.setAuthorId(userId);
            apCommentLike1.setCommentId(dto.getCommentId());
            apCommentLike1.setOperation((short) 0);
            mongoTemplate.save(apCommentLike1);
            //并修改评论信息的点赞数量( + 1)
            Query queryComment = Query.query(Criteria.where("id").is(dto.getCommentId()));
            Integer likes = apComment.getLikes() + 1;
            Update update = new Update();
            update.set("likes", likes);
            mongoTemplate.updateFirst(queryComment, update, ApComment.class);
            ApComment nowApComment = mongoTemplate.findOne(queryComment, ApComment.class);
            if (nowApComment.getLikes() >= 10 && nowApComment.getFlag() == 0) {
                commentHotService.hotCommentExecutor(nowApComment);
            }
        } else {
            //提示请勿重复点赞
            CustException.cust(AppHttpCodeEnum.NEED_UnLike, "请勿重复点赞");
        }
    }

}


